import React, { Component } from 'react';
import Record from './Record';
import RecordFrom from './RecordFrom';
import { api } from '../until/api'

class Records extends Component {
  constructor() {
    super();
    this.state = {
      error: null,
      isLoaded: false,
      records: []
    }
  }

  // 生命周期挂载
  componentDidMount() {
    // axios请求数据
    api.getAll().then(res => {
        this.setState({
          records: res.data,
          isLoaded: true
        })
    }).catch(error => this.setState({
        isLoaded: true,
        error
    }));
  }

  // 更新数据
  updataRecord(ind, data) {
    // const newRecords = this.state.records.map((item, index) => {
    //   if(index !== ind) {
    //     return item;
    //   }
    //   return { ...item, ...data };
    // });
    let newRecords = this.state.records
    newRecords[ind] = data
    this.setState({
      records: newRecords
    });
  }
  // 添加数据
  hanlderChange(data) {
    this.setState({
      error: null,
      isLoaded: true,
      records: [...this.state.records, data]
    })
  }
  // 删除数据
  delRecord(ind) {
    let newRecords = this.state.records
    newRecords.splice(ind, 1)
    this.setState({
      records: newRecords
    });
  }

  render() {
    const { error, isLoaded, records } = this.state;
    let recordsComponents;
    if (error) {
      recordsComponents = <div>Error: {error.message}</div>;
    } else if (!isLoaded) {
      recordsComponents = <div>Loading...</div>;
    } else {
      recordsComponents = (
        <div>
          <table className="table table-bordered">
            <thead>
              <tr>
                <th>日期（Date）</th>
                <th>标题（Title）</th>
                <th>数量（Amount）</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              {records.map((item, i) => 
                <Record record={item} ind={i} key={i} handleEditRecord={this.updataRecord.bind(this)} handleDel={this.delRecord.bind(this)} />
              )}
            </tbody>
          </table>
        </div>
      );
    }

    return (
      <div className="p-3">
        <h2>列表</h2>
        <RecordFrom onNewChange={this.hanlderChange.bind(this)}/>
        {recordsComponents}
      </div>
    )
  }
}

export default Records;
